package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.domain.AppLabelLike;
import com.ruoyi.app.domain.bo.AppLabelLikeBo;
import com.ruoyi.app.domain.vo.AppLabelLikeVo;
import com.ruoyi.app.domain.vo.AppLabelVo;
import com.ruoyi.app.domain.vo.UserVo;
import com.ruoyi.app.mapper.AppLabelLikeMapper;
import com.ruoyi.app.service.IAppLabelLikeService;
import com.ruoyi.app.service.IAppLabelTypeService;
import com.ruoyi.app.service.IAppUserService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.LikeStatus;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * APP用户标签喜欢Service业务层处理
 *
 * @author heike
 * @date 2023-01-13
 */
@RequiredArgsConstructor
@Service
public class AppLabelLikeServiceImpl implements IAppLabelLikeService {

    private final AppLabelLikeMapper baseMapper;
    private final IAppUserService appUserService;
    private final IAppLabelTypeService appLabelTypeService;

    /**
     * 查询APP用户标签喜欢
     */
    @Override
    public AppLabelLikeVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询APP用户标签喜欢列表
     */
    @Override
    public TableDataInfo<AppLabelLikeVo> queryPageList(AppLabelLikeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppLabelLike> lqw = buildQueryWrapper(bo);
        Page<AppLabelLikeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询APP用户标签喜欢列表
     */
    @Override
    public List<AppLabelLikeVo> queryList(AppLabelLikeBo bo) {
        LambdaQueryWrapper<AppLabelLike> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(AppLabelLike::getCreateTime);
        lqw.orderByDesc(AppLabelLike::getId);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询APP用户标签喜欢列表
     */
    @Override
    public List<AppLabelLikeVo> list(AppLabelLikeBo bo) {
        LambdaQueryWrapper<AppLabelLike> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(AppLabelLike::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public AppLabelLikeVo queryLikeLabel(Long userId, Long labelId) {
        LambdaQueryWrapper<AppLabelLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppLabelLike::getUserId, userId).eq(AppLabelLike::getLabelId, labelId);
        return baseMapper.selectVoOne(wrapper);
    }

    private LambdaQueryWrapper<AppLabelLike> buildQueryWrapper(AppLabelLikeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppLabelLike> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, AppLabelLike::getUserId, bo.getUserId());
        lqw.eq(bo.getLabelId() != null, AppLabelLike::getLabelId, bo.getLabelId());
        lqw.eq(bo.getTypeId() != null, AppLabelLike::getTypeId, bo.getTypeId());
        lqw.eq(StringUtils.isNotBlank(bo.getLikeStatus()), AppLabelLike::getLikeStatus, bo.getLikeStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AppLabelLike::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增APP用户标签喜欢
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AppLabelLikeBo bo) {
        AppLabelLike add = BeanUtil.toBean(bo, AppLabelLike.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改APP用户标签喜欢
     */
    @Override
    public Boolean updateByBo(AppLabelLikeBo bo) {
        AppLabelLike update = BeanUtil.toBean(bo, AppLabelLike.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppLabelLike entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除APP用户标签喜欢
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean deletes(Long userId) {
        LambdaQueryWrapper<AppLabelLike> labelLike = new LambdaQueryWrapper<>();
        labelLike.eq(AppLabelLike::getUserId, userId);
        return baseMapper.delete(labelLike) > 0;
    }

    @Override
    public Boolean setLabelLike(AppLabelLikeBo labelLikeBo) {
        LambdaUpdateWrapper<AppLabelLike> update = new LambdaUpdateWrapper<>();
        update.eq(AppLabelLike::getId, labelLikeBo.getId())
            .eq(AppLabelLike::getUserId, labelLikeBo.getUserId())
            .set(AppLabelLike::getCause, labelLikeBo.getCause())
            .set(AppLabelLike::getLikeStatus, LikeStatus.SUPER_LIKE.getCode());
        return baseMapper.update(null, update) > 0;
    }

    @Override
    public Boolean cancelLabelLike(Long id, Long userId) {
        LambdaUpdateWrapper<AppLabelLike> update = new LambdaUpdateWrapper<>();
        update.eq(AppLabelLike::getId, id)
            .eq(AppLabelLike::getUserId, userId)
            .set(AppLabelLike::getCause, null)
            .set(AppLabelLike::getLikeStatus, LikeStatus.LIKE.getCode());
        return baseMapper.update(null, update) > 0;

    }

    @Override
    public AppLabelVo info(AppLabelVo labelVo, Long uid) {
        AppLabelLikeBo likeBo = new AppLabelLikeBo();
        likeBo.setLabelId(labelVo.getId());
        likeBo.setLikeStatus(LikeStatus.LIKE.getCode());
        ArrayList<UserVo> userVos = new ArrayList<>();
        List<AppLabelLikeVo> appLabelLikeVos = queryList(likeBo);
        //获取当前用户的标签集合
        AppLabelLikeBo labelLikeBo = new AppLabelLikeBo();
        labelLikeBo.setUserId(uid);
        List<AppLabelLikeVo> myLabels = queryList(labelLikeBo);
        List<Long> collect = myLabels.stream().map(AppLabelLikeVo::getLabelId).collect(Collectors.toList());
        appLabelLikeVos.forEach(e -> {
            UserVo userVo = appUserService.queryByIdUserVo(e.getUserId());
            //好友标签共同数
            if (!e.getUserId().equals(uid)) {
                AppLabelLikeBo otherLikeBo = new AppLabelLikeBo();
                otherLikeBo.setUserId(e.getUserId());
                List<AppLabelLikeVo> otherLikes = queryList(otherLikeBo);
                long count = otherLikes.stream().filter(i -> collect.contains(i.getLabelId())).count();
                userVo.setCommonNumber((int) count);
            } else {
                userVo.setCommonNumber(0);
            }
            userVos.add(userVo);
        });
        labelVo.setUserLikeVos(userVos);
        //超级喜欢用户列表
        AppLabelLikeBo loveBo = new AppLabelLikeBo();
        loveBo.setLabelId(labelVo.getId());
        loveBo.setLikeStatus(LikeStatus.SUPER_LIKE.getCode());
        List<AppLabelLikeVo> loveVos = queryList(loveBo);
        ArrayList<UserVo> userLoveVos = new ArrayList<>();
        int end = Math.min(loveVos.size(), 3);
        for (int i = 0; i < end; i++) {
            AppLabelLikeVo e = loveVos.get(i);
            UserVo user = appUserService.queryByIdUserVo(e.getUserId());
            user.setCause(e.getCause());
            userLoveVos.add(user);
        }
        labelVo.setUserLoveVos(userLoveVos);
        labelVo.setTypeName(appLabelTypeService.queryById(labelVo.getTypeId()).getName());
        return labelVo;
    }

    @Override
    public int delete(Long id) {
        return baseMapper.deleteById(id);
    }
}
